package com.example.templatetodocx;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;
import pl.jsolve.templ4docx.core.Docx;
import pl.jsolve.templ4docx.variable.TableVariable;
import pl.jsolve.templ4docx.variable.TextVariable;
import pl.jsolve.templ4docx.variable.Variable;
import pl.jsolve.templ4docx.variable.Variables;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class TemplateToWordService {

    public File exportWord(){
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource templeteResource = pathMatchingResourcePatternResolver.getResource("classpath:/template/template.docx");
        Variables variables = genExportWordVar();
        Docx docx = null;
        File file = null;
        try {
            docx = new Docx(templeteResource.getInputStream());
            docx.fillTemplate(variables);
            String tempFile = "D:\\template.docx";
            file = new File(tempFile);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            docx.save(tempFile);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return file;
    }

    private Variables genExportWordVar() {
        Variables var = new Variables();
        //纯文字替换
        var.addTextVariable(new TextVariable("${a}", "文字替换"));
        //表格循环
        TableVariable tableVariable = new TableVariable();
        List<Variable> t1List = new ArrayList<Variable>();
        List<Variable> t2List = new ArrayList<Variable>();

        t1List.add(new TextVariable("${t1}","第一行第一列"));
        t1List.add(new TextVariable("${t1}","第二行第一列"));
        t2List.add(new TextVariable("${t2}","第一行第二列"));
        t2List.add(new TextVariable("${t2}","第二行第二列"));

        tableVariable.addVariable(t1List);
        tableVariable.addVariable(t2List);

        var.addTableVariable(tableVariable);

        return var;
    }

}
